// 转换值工具类
import { ConfigDetailType, ComponentConfig, InputListConfig } from '../library/page-object'
import Vue from 'vue'

/**
 * 添加属性转换的默认属性
 * @param item 需要改变值的item对象
 * @param configItem 判断的配置
 * @param inputListConfig 输入框的配置
 * @param newAttrObj 需要设置的对象
 */
export function addComponentConfigDefaultAttr(
  item: any,
  configItem: ComponentConfig,
  inputListConfig: InputListConfig,
  newAttrObj: { [key: string]: Function }
): void {
  switch (inputListConfig.component) {
    case ConfigDetailType.Select:
    case ConfigDetailType.Input:
    case ConfigDetailType.Textarea:
    case ConfigDetailType.InputNumber:
    default:
      if (!newAttrObj.hasOwnProperty('value')) {
        if (typeof item.mpdConfig[configItem.type][configItem.name] === 'boolean') {
          newAttrObj.value = item.mpdConfig[configItem.type][configItem.name]
        } else {
          newAttrObj.value = item.mpdConfig[configItem.type][configItem.name] || configItem.defaultValue
        }
      }
      break
  }
}

/**
 * 添加事件转换的默认事件
 * @param item 需要改变值的item对象
 * @param configItem 判断的怕配置
 * @param inputListConfig 输入框的配置
 * @param newEventObj 需要设置的对象
 */
export function addComponentConfigDefaultEvent(
  item: any,
  configItem: ComponentConfig,
  inputListConfig: InputListConfig,
  newEventObj: { [key: string]: Function }
): void {
  switch (inputListConfig.component) {
    case ConfigDetailType.Input:
    case ConfigDetailType.Textarea:
      if (!newEventObj.hasOwnProperty('change')) {
        newEventObj.change = function(e: Event) {
          Vue.set(item.mpdConfig[configItem.type], configItem.name, (e.target as HTMLInputElement).value || undefined)
        }
      }
      break
    case ConfigDetailType.Select:
    case ConfigDetailType.InputNumber:
    default:
      if (!newEventObj.hasOwnProperty('change')) {
        newEventObj.change = function(value: any) {
          if (typeof value === 'boolean') {
            Vue.set(item.mpdConfig[configItem.type], configItem.name, value)
          } else {
            Vue.set(item.mpdConfig[configItem.type], configItem.name, value || undefined)
          }
        }
      }
      break
  }
}
